<template>
  <div class="page-container">
    <!--工具栏-->
    <div class="toolbar" style="float:left;padding-top:10px;padding-left:15px;">
      <el-form :inline="true" :model="filters" :size="size">
        <el-form-item>
          <el-input v-model="filters.description" placeholder="菜单名称"></el-input>
        </el-form-item>
        <el-form-item>
          <perm-button icon="fa fa-search" label="搜索" perms="sys:perm:list" type="primary" @click="findTreeData()"/>
        </el-form-item>
        <el-form-item>
          <perm-button icon="fa fa-plus" label="新增" perms="sys:perm:add" type="success" @click="handleAdd"/>
        </el-form-item>
      </el-form>
    </div>
    <!--表格树内容栏-->
    <el-table :data="tableTreeDdata" stripe size="mini" style="width: 100%;"
              v-loading="loading" element-loading-text="拼命加载中" row-key="permId">
      <el-table-column prop="permId" header-align="center" align="center" width="100" label="ID">
      </el-table-column>
      <table-tree-column
        prop="description" header-align="center" treeKey="permId" width="250" label="菜单名称">
      </table-tree-column>
      <el-table-column  prop="permType" header-align="center" align="center" width="150" label="权限类型">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.permType === '目录'" size="small">目录</el-tag>
          <el-tag v-else-if="scope.row.permType === '菜单'" size="small" type="success">菜单</el-tag>
          <el-tag v-else-if="scope.row.permType === '按钮'" size="small" type="warning">按钮</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="permission" header-align="center" align="center" width="150" label="权限值">
      </el-table-column>
      <el-table-column
        prop="permUrl" header-align="center" align="center" width="150" label="菜单路由">
      </el-table-column>
      <el-table-column
        prop="parentName" header-align="center" align="center" width="150" label="上级菜单">
      </el-table-column>
      <el-table-column prop="icon" header-align="center" align="center" width="150" label="图标">
        <template slot-scope="scope">
          <i :class="scope.row.icon || ''"></i>
        </template>
      </el-table-column>
      <el-table-column
        prop="orderNum" header-align="center" align="center" label="排序">
      </el-table-column>
      <el-table-column
        fixed="right" header-align="center" align="center" width="185" label="操作">
        <template slot-scope="scope">
          <perm-button icon="fa fa-edit" label="编辑" perms="sys:perm:update" @click="handleEdit(scope.row)"/>
          <perm-button icon="fa fa-trash" label="删除" perms="sys:perm:delete" type="danger" @click="handleDelete(scope.row)"/>
        </template>
      </el-table-column>
    </el-table>
    <!-- 新增修改界面 -->
    <el-dialog :title="!dataForm.permId ? '新增' : '修改'" width="30%" :visible.sync="dialogVisible" :close-on-click-modal="false">
      <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="submitForm()"
               label-width="80px" :size="size" style="text-align:left;">
        <el-form-item label="权限类型" prop="permType">
          <el-radio-group v-model="dataForm.permType" @change="handlePermTypeChange">
            <el-radio-button v-for="(type, index) in menuTypeList" :label="type" :key="index">{{ type }}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="dataForm.permType + '名称'" prop="description">
          <el-input v-model="dataForm.description" :placeholder="dataForm.permType + '名称'"></el-input>
        </el-form-item>
        <el-form-item label="上级菜单" prop="parentName">
          <popup-tree-input
            :data="popupTreeData" :props="popupTreeProps" :prop="dataForm.parentName==null||dataForm.parentName==''?'顶级菜单':dataForm.parentName"
            :nodeKey="''+dataForm.parentId" :currentChangeHandle="handleTreeSelectChange">
          </popup-tree-input>
        </el-form-item>
        <el-form-item label="权限值" prop="permission">
          <el-input v-model="dataForm.permission" placeholder="如: sys:user:add, sys:user:edit, sys:user:delete"></el-input>
        </el-form-item>
        <el-form-item v-if="dataForm.permType !== '按钮'" label="菜单图标" prop="icon">
          <el-row>
            <el-col :span="22">
              <el-input v-model="dataForm.icon" v-popover:iconListPopover :readonly="false" placeholder="菜单图标名称（如：fa fa-home fa-lg）" class="icon-list__input"></el-input>
            </el-col>
            <el-col :span="2" class="icon-list__tips">
              <fa-icon-tooltip />
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item v-if="dataForm.permType === '菜单'" label="菜单路由" prop="permUrl">
          <el-input v-model="dataForm.permUrl" placeholder="如用户管理，Views目录下页面路径为 /Sys/User, 此处填写 /sys/user"></el-input>
        </el-form-item>
        <el-form-item label="排序编号" prop="orderNum">
          <el-input-number v-model="dataForm.orderNum" controls-position="right" :min="0" label="排序编号"></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button :size="size"  @click="dialogVisible = false">取消</el-button>
        <el-button :size="size"  type="primary" :loading="editLoading" @click="submitForm()">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import PopupTreeInput from '../../Component/PopupTreeInput/Index'
import PermButton from '../../Component/PermButton/Index'
import TableTreeColumn from '../../Component/TableTreeColumn/Index'
import FaIconTooltip from '../../Component/FaIconTooltip/Index'
export default {
    name: 'Perm',
    components: {
        TableTreeColumn,
        PermButton,
        PopupTreeInput,
        FaIconTooltip
    },
    data() {
        return {
            size: 'small',
            loading: false,
            editLoading: false,
            filters: {
                description: ''
            },
            tableTreeDdata: [],
            menuTypeList: ['目录', '菜单', '按钮'],
            dialogVisible: false,
            dataForm: {
                permId: 0,
                permission: '',
                description: '',
                permUrl: '',
                icon: '',
                permType: '目录',
                parentId: 0,
                parentName: '',
                orderNum: 0
            },
            dataRule: {
                description: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
                permission: [{ required: true, message: '权限值不能为空', trigger: 'blur' }]
            },
            popupTreeData: [],
            popupTreeProps: {
                label: 'description',
                children: 'children'
            }
        }
    },
    methods: {
    // 获取数据
        findTreeData: function() {
            this.loading = true
            const param = {
                description: this.filters.description
            }
            this.$api.perm.getPermList(param).then(res => {
                if (res && !res.success) {
                    this.$message({ message: res.message, type: 'error' })
                    this.loading = false
                    return
                }
                this.tableTreeDdata = res.data
                this.popupTreeData = this.getParentMenuTree(res.data)
                this.loading = false
            })
        },
        // 获取上级分类树
        getParentMenuTree: function(tableTreeDdata) {
            const parent = {
                parentId: 0,
                description: '顶级菜单',
                children: this.getFolderMenu(tableTreeDdata)
            }
            return [parent]
        },
        getFolderMenu: function(tableTreeDdata) {
            const folder = this.cloneObjectFn(tableTreeDdata)
            return this.filterMenu(folder)
        },
        // 解决vue深拷贝问题，复制对象变动会影响原数据，这里希望完成新的对象不在和原对象关联
        cloneObjectFn: function(obj) {
            return JSON.parse(JSON.stringify(obj))
        },
        filterMenu: function(tableTreeDdata) {
            const folder = tableTreeDdata.filter(item => item.permType !== '按钮')
            for (const item of folder) {
                if (item.children && item.children.length > 0) {
                    item.children = this.filterMenu(item.children)
                }
            }
            return folder
        },
        // 显示新增界面
        handleAdd: function() {
            this.dialogVisible = true
            this.dataForm = {
                permId: 0,
                permission: '',
                description: '',
                permUrl: '',
                icon: '',
                permType: '目录',
                parentId: 0,
                orderNum: 0
            }
        },
        // 显示编辑界面
        handleEdit: function(row) {
            this.dialogVisible = true
            Object.assign(this.dataForm, row)
        },
        // 删除
        handleDelete(row) {
            this.$confirm('确认删除选中记录吗？', '提示', {
                type: 'warning'
            }).then(() => {
                const params = this.getDeleteIds([], row)
                this.$api.perm.deletePerm(params).then(res => {
                    if (!res.success) {
                        this.$message({ message: res.message, type: 'error' })
                        return
                    }
                    this.findTreeData()
                    this.$message({ message: '删除成功', type: 'success' })
                })
            })
        },
        // 获取删除的包含子分类的id列表
        getDeleteIds(ids, row) {
            ids.push(row.permId)
            if (row.children != null) {
                for (let i = 0, len = row.children.length; i < len; i++) {
                    this.getDeleteIds(ids, row.children[i])
                }
            }
            return ids
        },
        // 分类树选中
        handleTreeSelectChange(data, node) {
            this.dataForm.parentId = data.permId
            this.dataForm.parentName = data.description
        },
        // 处理权限类型变化
        handlePermTypeChange(val) {
            if (val === '按钮') {
                this.dataForm.icon = ''
                this.dataForm.permUrl = ''
            }
            if (val !== '菜单') {
                this.dataForm.permUrl = ''
            }
        },
        // 表单提交
        submitForm() {
            var callback = (res) => {
                this.editLoading = false
                if (res.success) {
                    this.$message({ message: '操作成功', type: 'success' })
                    this.$refs['dataForm'].resetFields()
                    this.dialogVisible = false
                } else {
                    this.$message({
                        message: res.message,
                        type: 'error'
                    })
                }
                this.findTreeData()
            }
            this.$refs['dataForm'].validate(valid => {
                if (valid) {
                    this.$confirm('确认提交吗？', '提示', {}).then(() => {
                        this.editLoading = true
                        const params = Object.assign({}, this.dataForm)
                        // 处理枚举类型, ordinal
                        params.permType = this.menuTypeList.findIndex(item => item === params.permType)
                        if (!this.dataForm.permId) {
                            this.$api.perm.savePerm(params).then(res => {
                                callback(res)
                            })
                        } else {
                            this.$api.perm.updatePerm(params).then(res => {
                                callback(res)
                            })
                        }
                    })
                }
            })
        }
    },
    mounted() {
        this.findTreeData()
    }
}
</script>

<style scoped>
</style>
